package com.dreamchaser.familydevice.util.QYWeChat;

import com.alibaba.fastjson.JSON;
import com.dreamchaser.familydevice.util.HttpUtil;
import com.dreamchaser.familydevice.util.QYWeChat.BaseModel.AccessTokenModel;
import com.dreamchaser.familydevice.util.QYWeChat.BaseModel.AgentSendModel;
import com.dreamchaser.familydevice.util.QYWeChat.BaseModel.ResponseModelByWeChat;
import com.dreamchaser.familydevice.util.RedisHandleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 企业微信的应用消息
 */
@Component
public class AgentMsgUtil {

    String corpid = "ww973d3e6796db49c7";
    @Autowired
    RedisHandleUtil redisUtil;

    /**
     * 获取token
     *
     * @param corpsecret
     * @return
     */
    private String getAccessToken(String corpsecret) throws Exception {
        Object token = null;//redisUtil.getObject(corpsecret);
        AccessTokenModel accessTokenModel;
        if (token == null) {
            String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", corpid, corpsecret);
            String t = HttpUtil.doGet(url);
            accessTokenModel = JSON.parseObject(t, AccessTokenModel.class);
            if (accessTokenModel.errcode == 0) {
                redisUtil.setObject(corpsecret, accessTokenModel.access_token, 3600);
                return accessTokenModel.access_token;
            } else {
                throw new Exception(url);
            }
        } else {
            return (String) token;
        }
    }

    /**
     * @param corpsecret 应用Secret
     * @param agentId
     * @return
     */
    public ResponseModelByWeChat sendMessage(String toUsers, String corpsecret, Integer agentId, String content) {
        try {
            String token = getAccessToken(corpsecret);

            if (token == null) return null;

            String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
            AgentSendModel.TextModel text = new AgentSendModel().new TextModel(content);
            AgentSendModel model = new AgentSendModel(toUsers, agentId, text);

            String response = HttpUtil.doPost(url, JSON.toJSONString(model));
            System.out.println(response);
            return JSON.parseObject(response, ResponseModelByWeChat.class);
        } catch (Exception e) {
            System.out.println("---------请求异常---------\r\n url:" + e.getMessage());
            return new ResponseModelByWeChat(500, e.getMessage());
        }


    }
}
